/*
 * @Description: 编辑广告
 * @Author: kanglin
 * @Date: 2018-06-20 10:05:57
 * @Copyright: Created by Panxsoft.
 */

<style lang="less" scoped rel="stylesheet/less" type="text/less" >
    .advert-edit{

      .redirect_img_thumb {
        height: 50px;
        vertical-align: middle;
      }
    }
</style>

<template>
	<div class="advert-edit">
		<Form
			ref="formValidate"
			:model="formValidate"
			:rules="ruleValidate"
			:label-width="labelWidth(120,140)"
			name="edit__form">

      <Row>
        <Col span="20">
          <FormItem
            :label="$t('advert.name')"
            prop="name">
            <i-input
              v-model="formValidate.name"
              :placeholder="$t('advert.please_enter_name')"
              name="edit__name"/>
          </FormItem>
        </Col>
      </Row>

      <Row>
        <Col span="20">
          <Form-item
            :label="$t('advert.device_account')"
            :placeholder="$t('advert.please_select_device')"
            prop="device_account_ids">
            <Select
              :style="{width: '288px'}"
              v-model="formValidate.device_account_ids"
              :transfer="true"
              name="edit__name"
              multiple>
              <OptionGroup
                v-for="store in storeDevices"
                :key="'store' + store.id"
                :label="store.name">
                <Option
                  v-for="device in store.device_accounts"
                  :value="device.id"
                  :key="'device' + device.id">{{ device.account }}
                </Option>
              </OptionGroup>
            </Select>
          </Form-item>
        </Col>
      </Row>

			<Form-item
				:label="$t('advert.media_type')"
				prop="advert_type_id">

				<RadioGroup
					v-model="formValidate.advert_type_id"
					@on-change="handleGroupChange">
					<Radio
						:label="image"
						name="edit__image">
						<Icon type="images" />
						<span>{{ $t('advert.image') }}</span>
					</Radio>
					<Radio :label="video">
						<Icon
							type="social-youtube"
							name="edit__video"/>
						<span>{{ $t('advert.video') }}</span>
					</Radio>
				</RadioGroup>

			</Form-item>

			<Form-item
				:label="$t('advert.media')"
				prop="url">
				<!-- bos上传按钮组件 -->
				<bos-upload
					ref="bos_upload"
					:bos-config="bosConfig"
					:accept="accept"
					:auto-start="true"
					:file-type-reg-exp="fileTypeRegExp"
					:tips="file_name"
					name="edit__media"
					@added="handleFileAdded"
					@post-init="init"
					@progress="changeProgress"
					@error="handleError"
					@post="handlePostComplete"
					@validate="isValidateVideo"/>
				<p>{{ uploadTips }}</p>
			</Form-item>

			<Form-item
				v-if="formValidate.advert_type_id === image"
				:label="$t('advert.play_second')"
				prop="play_second">
				<InputNumber
					:max="60*60*12"
					:min="1"
					v-model="formValidate.play_second"
					name="edit__play_second"/>
			</Form-item>


      <!-- 选择跳转类型 -->
      <Row>
        <Col span="14">
          <Form-item
            v-if="isAdvertTypeImage()"
            :label="$t('advert.redirect_type')"
            prop="redirectable_type">

            <Select
              v-model="formValidate.redirectable_type"
              clearable
              @on-change="formValidate.redirectable_id = 0"
              name="create__redirectable_type"
            >
              <Option
                v-for="redirectable_type in redirectable_types"
                :value="redirectable_type.id"
                :key="'redirectable_type' + redirectable_type.id">{{ redirectable_type.name }}
              </Option>
            </Select>
          </Form-item>
        </Col>
      </Row>

      <!-- 选择整妆 -->
      <Row>
        <Col span="20">

          <!-- 选整妆 -->
          <Form-item
            v-if="packSelectionVisible()"
            :label="$t('advert.redirect_pack')"
            required
            prop="redirectable_id">

            <Select
              v-model="formValidate.redirectable_id"
              name="create__redirect_pack_id"
              filterable
            >
              <Option
                v-for="pack in packs"
                :value="pack.id"
                :key="'pack' + pack.id"
                :label="pack.name"
              >
                <img class="redirect_img_thumb" :src="pack.thumb"/>
                <span>{{pack.name}}</span>
              </Option>
            </Select>
          </Form-item>
        </Col>
      </Row>

      <!-- 选单品 -->
      <Row>
        <Col span="20">
          <Form-item
            v-if="assetSelectionVisible()"
            :label="$t('advert.redirect_product')"
            required
            prop="redirectable_id">

            <Select
              v-model="formValidate.redirectable_id"
              name="edit__redirect_product_id"
              filterable
            >
              <Option
                v-for="product in products"
                :value="product.id"
                :key="'product' + product.id"
                :label="product.name">
                <img class="redirect_img_thumb" :src="product.thumb_image && product.thumb_image.key"/>
                <span>{{product.name}}</span>
              </Option>
            </Select>
          </Form-item>
        </Col>
      </Row>

      <!-- 跳转网址 -->
      <Row>
        <Col span="20">
          <Form-item
            v-if="urlInputVisible()"
            :label="$t('advert.redirect_url')"
            required
            prop="redirect_url">

            <i-input
              v-model="formValidate.redirect_url"
              :placeholder="$t('advert.please_enter_url')"
              name="create__redirect_url"/>
          </Form-item>
        </Col>
      </Row>

      <!-- 提交 -->
			<Form-item>
				<Button
					type="primary"
					name="edit__submit"
					@click="handleSubmit('formValidate')">{{ $t('common.update') }}</Button>
			</Form-item>
		</Form>
	</div>
</template>

<script>
import bosUpload from 'src/views/component/bosupload';
import labelWidthMixin from 'src/views/mixins/labelWidthMixin';
import { $t } from 'src/i18n';
import { mapMutations } from 'vuex';
import { isUrlValidate } from 'src/utils/utils';

const [TYPE_IMAGE, TYPE_VIDEO] = [1, 2]; // 常量
const [REDIRECTABLE_TYPE_PACK, REDIRECTABLE_TYPE_PRODUCT, REDIRECTABLE_TYPE_URL]  = ['Pack', 'Product', 'Url'];

export default {
	name: 'AdvertEdit',
	components: {
		bosUpload,
	},
	mixins: [labelWidthMixin],
	props: {
		bosConfig: {
			type: Object,
			required: true,
		},
		storeDevices: {
			type: Array,
			required: true,
		},
		update: {
			type: Function,
			required: true,
		},
		advert: {
			type: Object,
			required: true,
		},
		packs: {
			type: Array,
			required: true,
		},
		products: {
			type: Array,
			required: true,
		},
	},
	data() {
		return {
			formValidate: {
				advert_type_id: 1, // 广告类别id 1 图片 2 视频
				name: null, // 广告名称
				content_key: null, // 广告内容 bos的key值 ，create方法获取bos 配置
				play_second: 15, // 播放时长
				device_account_ids: [], // 设备id，create 方法获取
        redirectable_type: '', // 跳转类型
        redirectable_id: 0, // 跳转ID
        redirect_url: '', // 跳转的网址
			}, // 更新表单数据

      /**
       * 表单验证规则
       * @see {@link https://github.com/yiminghe/async-validator}
       */
			ruleValidate: {
				name: [
					{
						required: true,
						message: this.$t('validate.required', { field: this.$t('advert.name') }),
						trigger: 'blur',
					},
				],
				play_second: [
					{
						required: true,
						type: 'number',
						message: this.$t('validate.required', { field: this.$t('advert.play_second') }),
						trigger: 'blur',
					},
				],
				device_account_ids: [
					{
						required: true,
						type: 'array',
						min: 1,
						message: this.$t('validate.required', { field: this.$t('advert.device_account') }),
						trigger: 'change',
					},
				],
        redirectable_id: [
          {
            validator: this.validateRedirectId.bind(this)
          }
        ],
        redirect_url: [{
          trigger: 'blur,change',
          validator: this.validateRedirectUrl.bind(this),
        }],
			},
			image: TYPE_IMAGE, // 指定当前选项的value值
			video: TYPE_VIDEO, // 指定当前选项的value值
			accepts: { // 设置 bos accept
				[TYPE_IMAGE]: 'image/gif, image/jpeg, image/png',
				[TYPE_VIDEO]: 'video/mp4',
			},
			regExps: { // 设置 校验文件类型的正则
				[TYPE_IMAGE]: /(image\/gif|image\/jpeg|image\/png)/i,
				[TYPE_VIDEO]: /video\/MP4/i,
			},
			tips: { // 提示
				[TYPE_VIDEO]: this.$t('advert.video_format'),
				[TYPE_IMAGE]: this.$t('advert.image_format'),
			},
			id: null,
			file_name: '',
			has_files: false,

      REDIRECTABLE_TYPE_PACK,
      REDIRECTABLE_TYPE_PRODUCT,
      REDIRECTABLE_TYPE_URL,

      redirectable_types: [
        {name: this.$t('advert.redirect_pack'), id: REDIRECTABLE_TYPE_PACK},
        {name: this.$t('advert.redirect_product'), id: REDIRECTABLE_TYPE_PRODUCT},
        {name: this.$t('advert.redirect_url'), id: REDIRECTABLE_TYPE_URL},
      ],
    };
	},
	computed: {
		accept() {
			const key = this.formValidate.advert_type_id;
			return this.accepts[key];
		},
		fileTypeRegExp() {
			const key = this.formValidate.advert_type_id;
			return this.regExps[key];
		},
		uploadTips() {
			const key = this.formValidate.advert_type_id;
			return this.tips[key];
		},
	},

	watch: {
		'formValidate.advert_type_id': {
			handler() {
				// this.removeFile();
				// this.file_name = ''; // 文件名
			},
		},
	},

	created() {
		this.id = this.advert.id;
		this.formValidate.advert_type_id = this.advert.advert_type_id || this.formValidate.advert_type_id;
		this.formValidate.name = this.advert.name;
		let default_second = 0;
		if (this.advert.advert_type_id === this.video) {
			default_second = 0;
		} else {
			default_second = 15;
		}
		this.formValidate.play_second = this.advert.play_second || default_second;
		this.formValidate.device_account_ids = this.advert.device_account_ids;
		this.file_name = this.parseFileName(this.advert.content_key);
		this.formValidate.redirectable_id = this.advert.redirectable_id;
		this.formValidate.redirectable_type = this.advert.redirectable_type;
		this.formValidate.redirect_url = this.advert.redirectable && this.advert.redirectable.url;
	},

	methods: {
    ...mapMutations('spinShow', [
      'showSpin',
      'closeSpin',
    ]),

    /**
     * 单选框改变时触发
     * @return {undefined}
     */
    handleGroupChange() {
      this.file_name = '';
      this.removeFile();
    },

    /**
     * 文件名替换
     * @param  {String} url {文件路径}
     * @return {undefined}
     */
    parseFileName(url) {
      if (url) {
        return url.replace(/^.+\//, ''); // 将文件名和拓展名的部分替换为''
      }
      return null;
    },

    /**
     * 重置 bos upload 组件
     * @return {undefined}
     */
    removeFile() {
      this.$refs.bos_upload.reset();
    },

    /**
     * bos上传进度显示
     * @param  {string} progress {需要设置给bos_key的值}
     * @return {undefined} {description}
     */
    changeProgress(progress) {
      const load_info = this.$t('advert.upload_progress', {value: progress});
      this.showSpin(load_info);
    },

    /**
     * 处理文件校验的结果
     * @param {boolean} isvalid
     */
    isValidateVideo() { //
      //
      // alert(`${isvalid}valid`);
    },


    /**
     * 上传完成回调
     * @param {Object} object {上传结束文件对象}
     * @return {undefined}
     */
    handlePostComplete({object}) {
      this.formValidate.content_key = object;
      if (this.formValidate.advert_type_id === TYPE_VIDEO) {
        this.formValidate.play_second = 0;
      }
      this.executeUpdate(this.formValidate);
    },

    /**
     *  执行更新
     * @param {Object} form {表单数据}
     * @return {undefined}
     */
    executeUpdate(form) {
      this.$refs.formValidate.validate((valid) => {
        if (valid) {
          this.update({id: this.id, form})
            .then((result) => {
              if (result) {
                this.$Message.success($t('common.update_success'));
              }
            })
            .catch((error) => {
              this.$Message.error(error.message);
            })
            .then(() => {
              this.closeSpin();
            });
        } else {
          this.$Message.error(this.$t('common.invalid_form_data'));
        }
      });
    },

    /**
     * bos上传按钮组件初始化回调
     * @return {undefined}
     */
    init() {
      // console.log('Bos have been initialized');
      // alert('Bos have been initialized')
    },

    /**
     * 上传的过程中出错的回调
     * @param  {type} error {错误信息}
     * @return {undefined}
     */
    handleError(error) {
      this.$Message.error(error.message);
    },

    /**
     * 更新表单
     * @return {undefined}
     */
    handleSubmit() {
      if (this.has_files || !this.file_name) { // 需要上传 以为切换了文件类型;
        this.$refs.bos_upload.start();
      } else {
        const form = {
          advert_type_id: this.formValidate.advert_type_id, // 广告类别id 1 图片 2 视频
          name: this.formValidate.name, // 广告名称
          // content_key: this.formValidate.advert_type_id, // 广告内容 bos的key值 ，create方法获取bos 配置
          play_second: this.formValidate.play_second, // 播放时长
          device_account_ids: this.formValidate.device_account_ids,
          redirectable_id: this.formValidate.redirectable_id,
          redirectable_type: this.formValidate.redirectable_type,
          redirect_url: this.formValidate.redirect_url,
        };
        this.executeUpdate(form);
      } // 直接 update
    },

    /**
     * 表单重置
     * @param  {String} name {表单上的ref的值}
     * @return {undefined}
     */
    handleReset(name) {
      this.removeFile();
      this.$refs[name].resetFields();
    },

    /**
     * bos上传按钮组件input改变时触发的回调
     * @return {undefined}
     */
    handleFileAdded() {
      this.has_files = true;
    },


    isAdvertTypeImage() {
      return this.formValidate.advert_type_id === TYPE_IMAGE;
    },

    /**
     * @return {boolean}
     */
    packSelectionVisible() {
      return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_PACK
        && this.isAdvertTypeImage()
    },
    /**
     * @return {boolean}
     */
    assetSelectionVisible() {
      return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_PRODUCT
        && this.isAdvertTypeImage()
    },

    /**
     * @return {boolean}
     */
    urlInputVisible() {
      return this.formValidate.redirectable_type === REDIRECTABLE_TYPE_URL
    },

    validateRedirectId(rule, value, callback) {
      if (this.formValidate.redirectable_type && !value) {
        callback(this.$t('validate.required', {field: this.$t('common.option')}));
      } else {
        callback();
      }
    },

    validateRedirectUrl(rule, value, callback) {
      const isRedirectTypeUrl = this.formValidate.redirectable_type === this.REDIRECTABLE_TYPE_URL;

      if (isRedirectTypeUrl && !isUrlValidate(value)) {
        callback(this.$t('validate.url', {field: this.$t('advert.redirect_url')}));
      } else {
        callback();
      }
    },
  }
};
</script>
